package com.market.cash.ui.activity

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.market.cash.R
import com.market.cash.configs.CashRootConfigs
import com.market.cash.databinding.CashKefuBinding
import com.market.cash.http.ApiService
import com.market.cash.http.IHttpCallback
import com.market.cash.pro.ProActivity
import com.market.cash.ui.adapter.CashRootKefuAdapter
import com.market.cash.utils.CashRootDensityUtil
import com.market.cash.utils.adapter.CashRootOnItemChildClickListener
import com.market.cash.utils.decoration.LinearSpacingItemDecoration
import com.market.cash.utils.event.CashRootEventType
import com.market.cash.utils.helper.CashRootCustomConfigsHelper
import com.market.cash.utils.helper.SharedHelper
import com.market.cash.utils.permission.OnPermissionCallback
import com.market.cash.utils.permission.Permission
import com.market.cash.utils.permission.XXPermissions
import org.json.JSONObject

/**
 * CashRoot
 * @Author wwdeng
 * @CreateTime: 2024/10/18 10:17
 * @Annotation：客服
 */
class KefuActivity: ProActivity() {
    lateinit var binding: CashKefuBinding
    var kefuAdapter: CashRootKefuAdapter? = null

    //产品名称
    private var pName = CashRootConfigs.CASHROOT_APPNAME
    //产品Token
    private var pToken = SharedHelper.getCashRootSPString(SharedHelper.CashRoot_SPKEY.CASHROOT_TOKEN)

    companion object {
        private const val INTENT_KEY_PRODUCT_NAME = "productName"
        private const val INTENT_KEY_PRODUCT_TOKEN = "productToken"
        private const val INTENT_KEY_EVENTREMARK = "eventRemark"
        fun start(context: Context, eventRemark: String,pName: String? = "",pToken: String? = "") {
            val intent = Intent(context, KefuActivity::class.java)
            intent.putExtra(INTENT_KEY_PRODUCT_NAME, pName)
            intent.putExtra(INTENT_KEY_PRODUCT_TOKEN, pToken)
            intent.putExtra(INTENT_KEY_EVENTREMARK, eventRemark)
            context.startActivity(intent)
        }
    }

    override fun getCashRootRootView(): View? {
        binding = CashKefuBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initCashRootView() {
        setCashRootTitleBarVisibility(View.VISIBLE)
        setCashRootTextTitle(getString(R.string.kefu_title))
        rootViewBinding.rootLayout.setBackgroundColor(Color.parseColor("#F9F9F9"))
        initCashRootKefuRecyclerView()

        //牌照信息
        if (!CashRootCustomConfigsHelper.isCashRootShowLicense()){
            binding.licenseLayout.removeAllViews()
            binding.licenseLayout.visibility = View.GONE
        } else {
            binding.licenseLayout.removeAllViews()
            binding.licenseLayout.addView(initCashRootLicenseView())
            binding.licenseLayout.visibility = View.VISIBLE
        }
    }

    override fun initCashRootListener() {
    }

    override fun initCashRootData() {
        val productName = intent.extras!!.getString(INTENT_KEY_PRODUCT_NAME,"")
        if (productName.isNotEmpty()){
            pName = productName
        }
        val productToken = intent.extras!!.getString(INTENT_KEY_PRODUCT_TOKEN,"")
        if (productToken.isNotEmpty()){
            pToken = productToken
        }
        //主产品
        if (this.pName == CashRootConfigs.CASHROOT_APPNAME){
            val commonInfo = SharedHelper.getCashRootSPString(SharedHelper.CashRoot_SPKEY.CASHROOT_COMMON)
            if (commonInfo.isEmpty()){
                loadCashRootKefuContactListAction()
                return
            }
            val data = JSONObject(commonInfo)
            setCashRootContactData(data)
        } else {
            loadCashRootKefuContactListAction()
        }
    }

    /**
     * 初始化Tab列表
     */
    private fun initCashRootKefuRecyclerView() {
        binding.textWorkTime.visibility = View.GONE
        binding.recyclerView.visibility = View.GONE
        binding.recyclerView.layoutManager = LinearLayoutManager(this)
        kefuAdapter = CashRootKefuAdapter(binding.recyclerView)
        binding.recyclerView.adapter = kefuAdapter
        val topDecoration = CashRootDensityUtil.dp2px(8f)
        val leftDecoration = CashRootDensityUtil.dp2px(16f)
        binding.recyclerView.addItemDecoration(LinearSpacingItemDecoration(leftDecoration, leftDecoration, topDecoration, topDecoration))
        binding.recyclerView.itemAnimator = DefaultItemAnimator()
        kefuAdapter!!.setOnItemChildClickListener(CashRootOnItemChildClickListener { _, childView, position ->
            val item = kefuAdapter!!.getItem(position)
            when (item.optString("type")) {
                "MOBILE" -> {//电话
                    if (XXPermissions.isGranted(this, Permission.CALL_PHONE)) {
                        onCallAction(item)
                    } else {
                        XXPermissions.with(this)
                            .permission(Permission.CALL_PHONE)
                            .request(object : OnPermissionCallback {
                                override fun onGranted(p0: MutableList<String>, p1: Boolean) {
                                    addCashRootEventPoint(CashRootEventType.CLICK.CASHROOT_CLICK_PERMISSION_SYSTEM_AGREE, Permission.CALL_PHONE)
                                    onCallAction(item)
                                }

                                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                                    addCashRootEventPoint(CashRootEventType.CLICK.CASHROOT_CLICK_PERMISSION_SYSTEM_DENY, Permission.CALL_PHONE)
                                    XXPermissions.startPermissionActivity(this@KefuActivity, Permission.CALL_PHONE)
                                }
                            })
                    }
                }

                else -> {//邮箱
                    onCopyAction(item)
                }
            }
        })
    }

    /**
     * 复制
     */
    private fun onCopyAction(item: JSONObject){
        val type = item.optString("type")
        addCashRootEventPoint(CashRootEventType.CLICK.CASHROOT_CLICK_KEFU_COPY,type + "：" + item.optString("value"))
        // 获取剪贴板管理器
        val clipboardManager = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        // 创建一个 ClipData 对象，将要复制的文本放入其中
        val clipData = ClipData.newPlainText("label", item.optString("value"))
        // 将 ClipData 对象放入剪贴板
        clipboardManager.setPrimaryClip(clipData)
        showCashRootToast(getString(R.string.kefu_copy_success))
    }

    /**
     * 拨号
     */
    private fun onCallAction(item: JSONObject){
        val type = item.optString("type")
        addCashRootEventPoint(CashRootEventType.CLICK.CASHROOT_CLICK_KEFU_DIAL,type + "：" + item.optString("value"))
        val callIntent = Intent(Intent.ACTION_DIAL)
        callIntent.setData(Uri.parse("tel:${item.optString("value")}"))
        startActivity(callIntent)
    }

    /**
     * 获取事件备注
     */
    private fun getEventRemark(): String{
        if (intent.extras != null){
            return intent.extras!!.getString(INTENT_KEY_EVENTREMARK,"")
        }
        return ""
    }

    /**
     * 获取联系方式列表
     */
    private fun setCashRootContactData(data: JSONObject){
        binding.textWorkTime.visibility = View.VISIBLE
        binding.recyclerView.visibility = View.VISIBLE
        val contactList = arrayListOf<JSONObject>()
        val customize = data.optJSONObject("customize")
        if (customize != null){
            val mobileList = customize.optString("mobile").split(",")
            for (i in mobileList.indices){
                val obj = JSONObject()
                obj.put("type","MOBILE")
                obj.put("value", mobileList[i])
                contactList.add(obj)
            }
            val emailList = customize.optString("email").split(",")
            for (i in emailList.indices){
                val obj = JSONObject()
                obj.put("type","EMAIL")
                obj.put("value", emailList[i])
                contactList.add(obj)
            }
        }
        kefuAdapter!!.data = contactList

        //工作时间
        //客服配置里没有配置工作时间，取主产品的工作时间展示
        var workDate = "Monday to Sunday"
        var workTime = "9:30am to 19:30pm."
        if (customize != null){
            val customData = customize.optJSONObject("customData")
            if (customData != null){
                if (!customData.has("workDate") || !customData.has("workTime")){
                    val commonCustomData = CashRootCustomConfigsHelper.getCashRootCustomData()
                    if (commonCustomData != null) {
                        customData.put("workDate",commonCustomData.optString("workDate"))
                        customData.put("workTime",commonCustomData.optString("workTime"))
                    }
                }
                workDate = customData.optString("workDate")
                workTime = customData.optString("workTime")
            }
        }
        binding.textWorkTime.text = String.format(getString(R.string.kefu_work_time),"$workDate $workTime")
    }

    /**
     * 获取联系方式列表
     */
    private fun loadCashRootKefuContactListAction(){
        showCashRootLoading()
        val params = JSONObject().apply {
            put("product",pName)
            put("token",pToken)
            put("path",ApiService.API_PATH.CASHROOT_API_APP_INFO_PATH)
        }
        val httpUrl = ApiService.getHttpUrl(ApiService.API_URL.CASHROOT_API_COMMON_URL)
        doPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code")) {
                    0 -> {//成功
                        val obj = data.optJSONObject("obj")
                        //保存所有数据
                        if (obj != null) {
                            setCashRootContactData(obj)
                        }
                    }
                }
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                hideCashRootLoading()
            }
        })
    }

    override fun onStart() {
        super.onStart()
        addCashRootEventPoint(CashRootEventType.PAGE.CASHROOT_PAGE_KEFU_START,getEventRemark())
    }

    override fun onDestroy() {
        super.onDestroy()
        addCashRootEventPoint(CashRootEventType.PAGE.CASHROOT_PAGE_KEFU_END,getEventRemark())
    }
}